package cn.tjnext.apply.web.controller;

import cn.tjnext.apply.contants.*;
import cn.tjnext.apply.dao.AdminDao;
import cn.tjnext.apply.dao.UserDao;
import cn.tjnext.apply.entity.AdminEntity;
import cn.tjnext.apply.entity.UserEntity;
import cn.tjnext.apply.repositories.AdminRepository;
import cn.tjnext.apply.repositories.UserRepository;
import cn.tjnext.apply.service.AbstractService;
import cn.tjnext.apply.service.AdminService;
import cn.tjnext.apply.service.ApplicantService;
import cn.tjnext.apply.service.UserService;
import cn.tjnext.apply.web.model.GenericEntityModel;
import cn.tjnext.apply.web.model.LoginModel;
import cn.tjnext.apply.web.model.PageModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 后台
 * Created by cp on 2017/7/28.
 */
@Controller
@RequestMapping("/back")
public class BackController extends AbstractController<AdminEntity, AdminRepository, AdminDao> {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ApplicantService applicantService;

    // 后台登录页
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        return PagePaths.BACK + PagePaths.LOGIN;
    }

    // 从登录页提交
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(LoginModel loginModel, HttpSession session, HttpServletResponse response, Model model) {
        // 验证登陆名密码
        LoginModel newLoginModel = adminService.login(loginModel);
        if (StringUtils.isEmpty(newLoginModel.getErrorMessage())) {
            try {
                adminService.createOrSave(newLoginModel.getAdminEntity());
            } catch (Exception e) {
                log.error("保存最后一次登录时间失败");
            }
            session.setAttribute("admin", newLoginModel);
            Cookie cookie = new Cookie("loginName", newLoginModel.getLoginName());
            if (newLoginModel.isRemember()) {
                cookie.setMaxAge(365 * 24 * 60 * 60);
            } else {
                cookie.setMaxAge(0);
            }
            response.addCookie(cookie);

            return "redirect:framework";
        }
        model.addAttribute("loginModel", newLoginModel);
        return getBasePath() + "/login";
    }

    /**
     * 后台首页
     * @return
     */
    @RequestMapping(value = "/framework", method = RequestMethod.GET)
    public String toFramework() {
        return getBasePath() + "/framework";
    }

    /**
     * 内容区
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String toIndex() {
        return getBasePath() + "/index";
    }

    // 注销
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return toLogin();
    }

    /**
     * 报名信息列表
     * @param pageModel
     * @param model
     * @return
     */
    @RequestMapping(value =  "/toList", method = RequestMethod.GET)
    protected String toList(PageModel pageModel, Model model) {
        model.addAttribute(BaseModelAttributeNames.DATA_LIST, applicantService
                .findAllByPage(pageModel, getPageSize()));
        model.addAttribute(BaseModelAttributeNames.DATA, ProductConstants.getProductList);
        return getBasePath() + BasePagePaths.LIST;
    }

    /**
     * 导出
     * @param response
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportDetail(HttpServletResponse response) {
        // 导出excel
        HSSFWorkbook workbook = applicantService.export(ProductConstants.getProductList);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            if (workbook == null) {
                response.setCharacterEncoding("utf-8");
                response.setHeader("contentType","text/html; charset=utf-8");

                outputStream.write(("没有报名信息").getBytes());
            } else {
                String fileName = "报名信息表.xls" ;
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
                workbook.write(outputStream);
            }
        } catch (IOException e) {
            log.error("报名信息导出失败", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("报名信息s导出失败：关闭response.outputStream时出错", e);
            }
        }

    }

    @Override
    protected String getBasePath() {
        return PagePaths.BACK;
    }

    @Override
    protected AbstractService<AdminEntity, AdminRepository, AdminDao> getService() {
        return adminService;
    }


    @Override
    protected AdminEntity getNewEntity() {
        return new AdminEntity();
    }

    @Override
    protected GenericEntityModel<AdminEntity> createEntityModel(AdminEntity entity) {
        return null;
    }

}
